package com.cl.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cl.domain.TaskInfo;
import com.cl.engine.TaskInfoPrivoder;
import com.cl.safe.R;
import com.cl.utils.SystemInfoUtils;

public class TaskManagerActivity extends Activity {
	private LinearLayout ll_loading;
	private ListView lv_task_manager;
	private TaskInfo taskInfo;
	private List<TaskInfo> allTaskInfos;
	private List<TaskInfo> userTaskInfos;
	private List<TaskInfo> sysTaskInfos;
	private MyAdapter adapter;
	private TextView tv_process_count;
	private TextView tv_mem_info;
	private TextView tv_status;
	private long availMem;
	private long totalMem;
	private int countProcess;
	private Button bt1;
	private Button bt2;
	private Button bt3;
	private Button bt4;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task_manager);
		tv_process_count = (TextView) findViewById(R.id.tv_process_count);
		tv_mem_info = (TextView) findViewById(R.id.tv_mem_info);
		tv_status = (TextView) findViewById(R.id.tv_status);
		lv_task_manager = (ListView) findViewById(R.id.lv_task_manager);
		ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
		bt1 = (Button) findViewById(R.id.bt1);
		bt2 = (Button) findViewById(R.id.bt2);
		bt3 = (Button) findViewById(R.id.bt3);
		bt4 = (Button) findViewById(R.id.bt4);
		
		fillData();
		lv_task_manager.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if(userTaskInfos != null && sysTaskInfos != null) {
					if(firstVisibleItem > userTaskInfos.size()) {
						tv_status.setText("系统进程：" + sysTaskInfos.size() + "个");
					}else {
						tv_status.setText("用户进程：" + userTaskInfos.size() + "个");
					}
				}
				
			}
		});
		
		lv_task_manager.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TaskInfo taskInfo;
				if(position == 0) {
					return;
				}else if(position <= userTaskInfos.size()) {//列表展示用户
					int newPosition = position - 1;
					taskInfo = userTaskInfos.get(newPosition);
				}else if(position == (userTaskInfos.size() + 1)) {
					return;
				}else {//列表展示系统
					int newPosition = position - 2 - userTaskInfos.size();
					taskInfo = sysTaskInfos.get(newPosition);
				}
				if(getPackageName().equals(taskInfo.getPackname())) {
					return;
				}
				if(taskInfo.isChecked()) {
					taskInfo.setChecked(false);
					ViewHolder holder = (ViewHolder) view.getTag();
					holder.cb_status.setChecked(false);
				}else {
					taskInfo.setChecked(true);
					ViewHolder holder = (ViewHolder) view.getTag();
					holder.cb_status.setChecked(true);
				}
			}
		});
	}
	private void fillData() {
		//加载数据，进度条可见
				ll_loading.setVisibility(View.VISIBLE);
				new Thread(){
					public void run() {
						allTaskInfos = TaskInfoPrivoder.getTaskInfos(getApplicationContext());
						userTaskInfos = new ArrayList<TaskInfo>();
						sysTaskInfos = new ArrayList<TaskInfo>();
						for(TaskInfo taskInfo :	allTaskInfos) {
							if(taskInfo.isUserTask()) {
								userTaskInfos.add(taskInfo);
							}else {
								sysTaskInfos.add(taskInfo);
							}
						}
						
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								//数据加载完毕，进度条不可见
								ll_loading.setVisibility(View.INVISIBLE);
								if(adapter == null) {
									adapter = new MyAdapter();
									lv_task_manager.setAdapter(adapter);
								}else {
									adapter.notifyDataSetChanged();
								}
								setTitle();
								bt1.setFocusable(true);
								bt1.setClickable(true);
								bt2.setFocusable(true);
								bt2.setClickable(true);
								bt3.setFocusable(true);
								bt3.setClickable(true);
								bt4.setFocusable(true);
								bt4.setClickable(true);
								
							}
						});
					};
				}.start();
	}
	private void setTitle() {
		availMem = SystemInfoUtils.getAvailMem(this);
		totalMem = SystemInfoUtils.getTotalMem(this);
		countProcess = SystemInfoUtils.getRunningProcessCount(this);
		tv_process_count.setText("运行中的进程：" + countProcess + "个");
		tv_mem_info.setText("剩余/总内存："+ Formatter.formatFileSize(this, availMem) + "/"
				+ Formatter.formatFileSize(this, totalMem));
	}
	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
			if(sp.getBoolean("isUserTaskShow", false)) {
				return userTaskInfos.size()+1;
			}else {
				return userTaskInfos.size()+1+sysTaskInfos.size()+1;
			}
		}
		@Override
		public Object getItem(int position) {
			return null;
		}
		@Override
		public long getItemId(int position) {
			return 0;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TaskInfo taskInfo;
			if(position == 0) {
				TextView tv = new TextView(getApplicationContext());
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setText("用户进程：" + userTaskInfos.size() + "个");
				return tv;
			}else if(position <= userTaskInfos.size()) {//列表展示用户软件
				int newPosition = position - 1;
				taskInfo = userTaskInfos.get(newPosition);
			}else if(position == (userTaskInfos.size() + 1)) {
				TextView tv = new TextView(getApplicationContext());
				tv.setBackgroundColor(Color.GRAY);
				tv.setTextColor(Color.WHITE);
				tv.setText("系统进程：" + sysTaskInfos.size() + "个");
				return tv;
			}else {//列表展示系统软件
				int newPosition = position - 2 - userTaskInfos.size();
				taskInfo = sysTaskInfos.get(newPosition);
			}
			
			ViewHolder holder = new ViewHolder();
			View view;
			if(convertView != null && convertView instanceof RelativeLayout) {
				view = convertView;
				holder = (ViewHolder) view.getTag();
			}else {
				view = View.inflate(TaskManagerActivity.this, R.layout.list_item_taskinfo, null);
				holder.iv_task_icon = (ImageView) view.findViewById(R.id.iv_task_icon);
				holder.tv_task_name = (TextView) view.findViewById(R.id.tv_task_name);
				holder.tv_task_memsize = (TextView) view.findViewById(R.id.tv_task_memsize);
				holder.cb_status = (CheckBox) view.findViewById(R.id.cb_status);
			
				
				view.setTag(holder);
			}
			holder.iv_task_icon.setImageDrawable(taskInfo.getIcon());
			holder.tv_task_name.setText(taskInfo.getName());
			holder.tv_task_memsize.setText("内存占用："
					+ Formatter.formatFileSize(getApplicationContext(),
							taskInfo.getMemsize()));
			holder.cb_status.setChecked(taskInfo.isChecked());
			if(getPackageName().equals(taskInfo.getPackname())) {
				holder.cb_status.setVisibility(View.INVISIBLE);
			}else {
				holder.cb_status.setVisibility(View.VISIBLE);
			}
			return view;
		}
		
	}
	class  ViewHolder {
		ImageView iv_task_icon;
		TextView tv_task_name;
		TextView tv_task_memsize;
		CheckBox cb_status;
	}
	public void selectAll(View v) {
		for(TaskInfo info:allTaskInfos) {
			if(getPackageName().equals(info.getPackname())) {
				continue;
			}
			info.setChecked(true);
		}
		adapter.notifyDataSetChanged();
	}
	public void selectOppo(View v) {
		for(TaskInfo info:allTaskInfos) {
			if(getPackageName().equals(info.getPackname())) {
				continue;
			}
			info.setChecked(!info.isChecked());
		}
		adapter.notifyDataSetChanged();
	}
	public void killAll(View v) {
		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		int count = 0;
		long savedMem = 0;
		// 记录那些被杀死的条目
		List<TaskInfo> killedTaskinfos = new ArrayList<TaskInfo>();
		for(TaskInfo info:allTaskInfos) {
			if(info.isChecked()) {
				am.killBackgroundProcesses(info.getPackname());
				if(info.isUserTask()) {
					userTaskInfos.remove(info);
					
				}else {
					sysTaskInfos.remove(info);
				}
				savedMem += info.getMemsize();
				killedTaskinfos.add(info);
				count++;
				
			}
		}
		allTaskInfos.removeAll(killedTaskinfos);
		adapter.notifyDataSetChanged();
		Toast.makeText(this,
				"杀死了" + count + "个进程，释放了"+ Formatter.formatFileSize(this, savedMem) + "的内存",
				1).show();
		countProcess -= count;
		availMem += savedMem;
		tv_process_count.setText("运行中的进程：" + countProcess + "个");
		tv_mem_info.setText("剩余/总内存："
				+ Formatter.formatFileSize(this, availMem) + "/"
				+ Formatter.formatFileSize(this, totalMem));
	}
	/**
	 * 进入设置
	 * 
	 * @param view
	 */
	public void enterSetting(View view) {
		Intent intent = new Intent(this, TaskSettingActivity.class);
		startActivityForResult(intent, 0);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		adapter.notifyDataSetChanged();
		super.onActivityResult(requestCode, resultCode, data);
	}
}
